package cn.com.miao.lynx.common.core.syntactic

import cn.hutool.json.JSONObject
import com.querydsl.core.types.ExpressionUtils
import com.querydsl.core.types.Ops
import com.querydsl.core.types.dsl.BooleanExpression
import com.querydsl.core.types.dsl.Expressions
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.data.jpa.domain.Specification
import org.springframework.web.bind.annotation.ExceptionHandler
import java.lang.reflect.Method
import java.util.*
import javax.persistence.criteria.Predicate

/**
 * EntityBuilder
 * @title: EntityBuilder
 * @description:
 * @author: dengmiao
 * @create: 2019-12-31 21:07
 **/
/*internal */class EntityBuilder {

    companion object Factory {

        /**
         * 构造query条件的Expression
         * 将传递的参数自动绑定到Entity上
         *
         * @param  obj
         * @return BooleanExpression
         */
        @ExceptionHandler(Throwable::class)
        fun matchSelectiveAttrExpressions(obj: Any): BooleanExpression? {
            val c = obj.javaClass
            var rv: BooleanExpression? = null
            val fs = c.declaredFields
            for (i in fs.indices) {
                val f = fs[i]
                f.isAccessible = true //设置些属性是可以访问的
                val `val` = f.get(obj)//得到此属性的值
                if (`val` != null) {
                    val ce1 = Expressions.stringPath(lowerCaseClassName(c.simpleName) + "." + f.name)
                    val ce2 = ExpressionUtils.toExpression(`val`)
                    val pred = Expressions.booleanOperation(Ops.EQ, ce1, ce2)
                    rv = if (rv != null) rv.and(pred) else pred
                }
            }

            return rv
        }

        /**
         * 构造update的Enity
         * 将传递的参数绑定到该id的Entity上，
         * 设置成新的Entity，id不变，再到数据库update
         *
         * @param obj1, obj2
         * @return Any2
         */
        @Throws(Exception::class)
        fun matchSelectiveEntity(obj1: Any, obj2: Any): Any {
            val fields = obj1.javaClass.declaredFields
            // 遍历所有属性
            for (j in fields.indices) {
                val name = fields[j].name
                if (fields[j].get(obj1) != null && "createdAt" != name && "createdBy" != name) {
                    val args = arrayOfNulls<Class<*>>(1)
                    args[0] = fields[j].type
                    val c = obj1.javaClass
                    val methodName = "set" + upperCaseClassName(name)
                    var method: Method?
                    method = c.getMethod(methodName, *args)
                    method!!.invoke(obj2, fields[j].get(obj1))
                }
            }
            return obj2
        }

        /**
         * 创建分页请求.
         * pageNumber 从 1 开始
         */
        @Throws(Exception::class)
        fun buildPageRequest(jsonObject: JSONObject): PageRequest {
            val pageNumber = Integer.parseInt(jsonObject["pageNumber"].toString())
            val pageSize = Integer.parseInt(jsonObject["pageSize"].toString())

            val sortArray = jsonObject.getJSONArray("sort")
            val sortList = ArrayList<Sort.Order>()
            for (i in sortArray.indices) {
                val ascFlag = sortArray.getJSONObject(i)["asc"].toString()
                var order: Sort.Order?
                order = if ("true" == ascFlag) {
                    Sort.Order(Sort.Direction.ASC, sortArray.getJSONObject(i)["field"].toString())
                } else {
                    Sort.Order(Sort.Direction.DESC, sortArray.getJSONObject(i)["field"].toString())
                }
                sortList.add(order)
            }
            return PageRequest.of(pageNumber - 1, pageSize, Sort.by(sortList))
        }

        /**
         * 创建动态查询条件组合.
         */
        @Throws(Exception::class)
        fun <T> buildSpecification(jsonObject: JSONObject): Specification<T> {
            val criteriaArray = jsonObject.getJSONArray("criteria")
            return Specification { root, /*criteriaQuery*/_, criteriaBuilder ->
                val predicates = ArrayList<Predicate>()
                for (i in criteriaArray.indices) {
                    val field = criteriaArray.getJSONObject(i)["field"].toString()
                    val value = criteriaArray.getJSONObject(i)["value"].toString()
                    val operator = criteriaArray.getJSONObject(i)["operator"].toString()

                    if ("eq" == operator) {
                        predicates.add(criteriaBuilder.equal(root.get<Any>(field), value))
                    }
                    when (operator) {
                        "eq" -> predicates.add(criteriaBuilder.equal(root.get<Any>(field), value))
                        "like" -> predicates.add(criteriaBuilder.like(root.get<Any>(field).`as`(String::class.java), "$value%"))
                        // to be continued
                    }
                }
                criteriaBuilder.and(*predicates.toTypedArray())
            }
        }


        private fun lowerCaseClassName(name: String): String {
            return name.substring(0, 1).toLowerCase() + name.substring(1)
        }

        private fun upperCaseClassName(name: String): String {
            return name.substring(0, 1).toUpperCase() + name.substring(1)
        }
    }
}